package com.example.servlet;

import com.example.model.WrongQuestionDAO;
import com.example.model.User;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

@WebServlet("/wrong-questions")
public class WrongQuestionServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        try (Connection conn = DBUtil.getConnection()) {
            WrongQuestionDAO dao = new WrongQuestionDAO(conn);
            
            int page = 1;
            if (request.getParameter("page") != null) {
                try {
                    page = Integer.parseInt(request.getParameter("page"));
                } catch (NumberFormatException e) {
                    // 使用默认值1
                }
            }
            
            int pageSize = 10;
            int offset = (page - 1) * pageSize;
            
            List<Map<String, Object>> wrongQuestions = dao.getWrongQuestions(user.getId(), offset, pageSize);
            int totalCount = dao.countWrongQuestions(user.getId());
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            
            request.setAttribute("wrongQuestions", wrongQuestions);
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("totalCount", totalCount);
            
            request.getRequestDispatcher("wrong-questions.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "Error: " + e.getMessage());
            request.getRequestDispatcher("wrong-questions.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 